package com.ns.sbs.oauth.cur;

import com.ns.basic.dict.service.IDictEntryService;
import com.ns.basic.server.service.IServerMenuService;
import com.ns.basic.server.service.IServerService;
import com.ns.core.annotations.ReqLog;
import com.ns.core.sentinel.LimitType;
import com.ns.core.sentinel.RateLimiter;
import com.ns.core.utils.sg.ResultOk;
import com.ns.core.vo.login.ServObjVO;
import com.ns.core.vo.login.SucObjVO;
import com.ns.sbs.oauth.menu.service.IMenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 服务WEB接口
 *
 * @author lw
 * @since 2024/09/11
 */
@RestController
@RequestMapping
@RequiredArgsConstructor
@CrossOrigin
public class CurrentController {

    private final IMenuService menuService;
    private final IServerMenuService serverMenuService;
    private final IServerService serverService;
    private final IDictEntryService dictEntryService;

    /**
     * 当前服务菜单
     *
     * @param id 服务id
     */
    @GetMapping("current/menus")
    @ReqLog(module = "服务菜单模块", name = "查询")
    @RateLimiter(time = 5, count = 15, limitType = LimitType.IP)
    public ResultOk getCurrentMenus(Long id) {
        AuthTreeVO tree = new AuthTreeVO();
        tree.setBt(menuService.getBasicMenu());
        tree.setPermissions(serverMenuService.getPermissions(id));
        return ResultOk.getSuccessData(tree);
    }

    /**
     * 根据code获取服务及服务拥有的权限
     *
     * @param code 用户名
     */
    @GetMapping("/cur/{code}")
    @ReqLog(module = "用户模块", name = "根据code获取服务", authFlag = false)
    @RateLimiter(time = 5, count = 15, limitType = LimitType.IP)
    public ResultOk getByCode(@PathVariable String code) {
        SucObjVO sucObjVO = new SucObjVO();
        ServObjVO servObjVO = serverService.getByCode(code);
        List<ServObjVO> curs = new ArrayList<>();
        curs.add(servObjVO);
        sucObjVO.setCurs(curs);
        // 当前菜单
        List<Long> holdMenus = serverMenuService.getServerMenus(servObjVO.getId());
        sucObjVO.setM(menuService.getDynamicMenu(holdMenus));
        // 权限菜单码
        sucObjVO.setAuthCodes(menuService.getMenuCode(holdMenus));
        // 字典
        sucObjVO.setGd(dictEntryService.listBy());
        return ResultOk.getSuccessData(sucObjVO);
    }
}
